package com.sinosoft.cnmuseum.utils;


import java.io.File;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

import com.sinosoft.dbtools.operate.single.DBSingleTableActorMgr;

public class Table2Dao {
	public final static String projectPath = "C:\\Users\\wangli\\git\\cnmuseum\\";//C:\Users\wangli\git\dpm_da
	public final static String entityPackageName = "com.sinosoft.cnmuseum.dao";
	public final static String dbDriver = "com.mysql.jdbc.Driver";
	//public final static String dbDriver = "com.p6spy.engine.spy.P6SpyDriver";
	public final static String dbURL = "jdbc:mysql://192.168.100.152:3306/cnmuseum?useUnicode=true&amp;characterEncoding=UTF-8";
	public final static String dbUser = "root";
	public final static String dbPass = "root";

	public static void main(String[] args) throws Exception {
		Table2Dao table2entity = new Table2Dao();
		
		//创建实体文件的路径
		File entityPackagePath = new File(projectPath + "src\\"+ entityPackageName.replace(".", "\\\\"));
		if (!entityPackagePath.exists())
			entityPackagePath.mkdirs();
		
		//从数据库中获取取table列表
		List<String> tableNameList = table2entity.getTableNameList();
		for (String tableName : tableNameList) {
			//if("base_org".equals(tableName)){
				tableName = table2entity._m_firstToUpperCase(tableName);
				System.out.println("table name:" + tableName);
				table2entity.packEntityAndConfig(tableName);
			//}
		}
	}
	
	
	public String  delUnderLine(String s){
		if(s.indexOf("_")<0){
			return  _m_firstToLowCase(s.toLowerCase());
		}
		s = s.toLowerCase();
		String[] arr = s.split("_");
		for(int i=0;i<arr.length;i++){
			arr[i] = _m_firstToUpperCase(arr[i]);
		}
		String result = "";
		for(int i=0;i<arr.length;i++){
			result= result +arr[i];
		}
		return result;
	}
	
	protected void packEntityAndConfig(String tableName) throws Exception {
		//表的所有域
		String oldtablename = tableName;
		tableName = _m_firstToUpperCase(delUnderLine(tableName.toLowerCase()));
		//创建class文件
		File className = new File(projectPath + "src\\"+ entityPackageName.replace(".", "\\\\") + "\\\\" + tableName+ "Dao"+ ".java");
		if (!className.exists())
			className.createNewFile();
		else{
			className.delete();
			className.createNewFile();
		}
		
		PrintWriter classWriter = new PrintWriter(className, "UTF-8");
		classWriter.println("package " + entityPackageName + ";\n");
		classWriter.println("\nimport com.sinosoft.dbtools.operate.single.DBSingleTableActorMgr;\n\n");
		classWriter.println("public class "+ tableName + "Dao"+ " extends BaseDao{\n");
		
		
		classWriter.println("\tpublic "+ tableName + "Dao"+ "() {");
		classWriter.println("\t\tthis.actor = DBSingleTableActorMgr.getDBSingleTableActor(\""+oldtablename+"\");");
		classWriter.println("\t}\n");
		
		classWriter.println("}");
		classWriter.flush();
		classWriter.close();
		// 打包实体类 end //////////////////////////////
		
	}
	/**
	 * 如果一个字段包括表名和id的话，则去掉表明只保留id
	 * @param fields
	 * @return
	 */
	public String delTableName(Field field,String s){
		if(field.isPrimaryKey()){
			return "id";
		}
		return s;
	}
	protected String _m_getPrimaryKeyColumn(Field[] fields) {
		String pkName = null;
		for (int i = 0; i < fields.length; i++)
			if (fields[i].isPrimaryKey()) {
				pkName = fields[i].getName();
				break;
			}
		return pkName;
	}

	protected String _m_toAttributeString(String _p_attr) {
		if (_p_attr == null)
			return null;
		char[] _v_charArray = _p_attr.toCharArray();
		if (_v_charArray.length > 0) {
			_v_charArray[0] = Character.toLowerCase(_v_charArray[0]);
			if (_v_charArray.length > 1)
				_v_charArray[1] = Character.toLowerCase(_v_charArray[1]);
		}
		return new String(_v_charArray);
	}

	protected String _m_firstToUpperCase(String _p_String) {
		if (_p_String == null)
			return null;
		char[] _v_charArray = _p_String.toCharArray();
		if (_v_charArray.length > 0)
			_v_charArray[0] = Character.toUpperCase(_v_charArray[0]);
		return new String(_v_charArray);
	}
	
	protected String _m_allToUpperCase(String _p_String) {
		if (_p_String == null)
			return null;
		return _p_String.toUpperCase();
	}
	
	protected String _m_firstToLowCase(String _p_String) {
		if (_p_String == null)
			return null;
		char[] _v_charArray = _p_String.toCharArray();
		if (_v_charArray.length > 0)
			_v_charArray[0] = Character.toLowerCase(_v_charArray[0]);
		return new String(_v_charArray);
	}
	protected Field[] getTableFileds(String tableName) throws Exception {
		Connection conn = null;
		PreparedStatement stmt = null;
		Field[] tableFields = null;
		conn = _m_getConnection();
		ResultSet rs1 = conn.getMetaData()
				.getPrimaryKeys(null, null, tableName);
		String primaryKey = null;
		while (rs1.next()) {
			primaryKey = rs1.getString(4);
		}
		stmt = conn.prepareStatement("select * from " + tableName);
		ResultSet rs = stmt.executeQuery();
		ResultSetMetaData md = rs.getMetaData();
		int colCount = md.getColumnCount();
		tableFields = new Field[colCount];
		
		
		
		for (int i = 0; i < tableFields.length; i++) {
			String colName = md.getColumnName(i + 1);
			String colType = md.getColumnTypeName(i + 1);
			stmt=conn.prepareStatement("select COLUMN_COMMENT from INFORMATION_SCHEMA.COLUMNS Where table_name = '"+tableName+"'  AND table_schema = 'centre_db'  AND column_name = '"+colName+"'");
			ResultSet rs11 = stmt.executeQuery();
			System.out.println(rs11.toString());
			String comment = "";
			if(rs11.next()){
				comment =  rs11.getString("COLUMN_COMMENT");
			}
			boolean isPK = colName.equals(primaryKey);
			tableFields[i] = new Field(colName, colType, isPK,comment);
			tableFields[i].setAutoIncrease(md.isAutoIncrement(i + 1));
			tableFields[i].setJavaType(md.getColumnClassName(i + 1));
		}
		if (stmt != null)
			stmt.close();
		if (conn != null)
			conn.close();
		return tableFields;
	}

	protected List<String> getTableNameList() throws Exception {
		List<String> _v_tableNameList = new ArrayList<String>();
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		conn = _m_getConnection();
		stmt = conn.prepareStatement("show tables");
		rs = stmt.executeQuery();
		while (rs.next())
			_v_tableNameList.add(rs.getString(1));
		if (stmt != null)
			stmt.close();
		if (conn != null)
			conn.close();
		if (rs != null)
			rs.close();
		return _v_tableNameList;
	}

	protected Connection _m_getConnection() throws Exception {
		Class.forName(dbDriver);
		Connection conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
		return conn;
	}

}

class Field2 {

	public String name = null;
	public String type = null;
	public boolean primaryKey = false;
	public boolean autoIncrease = false;
	public String javaType = null;
	public String comment = null;
	
	
	public String getComment() {
		return comment;
	}

	public void setComment(String comment) {
		this.comment = comment;
	}

	public Field2(String name, String type, boolean primaryKey,String comment) {
		this.name = name;
		this.type = type;
		this.primaryKey = primaryKey;
		this.comment = comment;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public boolean isPrimaryKey() {
		return primaryKey;
	}

	public void setPrimaryKey(boolean primaryKey) {
		this.primaryKey = primaryKey;
	}

	public String getType() {
		if(type.toUpperCase().equals("INT")){
			return "INTEGER";
		}
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public boolean isAutoIncrease() {
		return autoIncrease;
	}

	public void setAutoIncrease(boolean autoIncrease) {
		this.autoIncrease = autoIncrease;
	}

	public String getJavaType() {
		return javaType;
	}

	public void setJavaType(String javaType) {
		this.javaType = javaType;
	}
}
